<template>
  <!-- class="project-list-container" -->
  <div>
    <div class="list-h">
      <div></div>
      <!-- <div style="margin-bottom: 20px">
        <el-button
          type="primary"
          v-auth="`funds-statistics-month`"
          @click="handleMonth"
          >月度支出填报</el-button
        >
        <el-button
          type="primary"
          v-auth="`funds-statistics-year`"
          @click="handleYear"
          >年度预算填报</el-button
        >
        <el-button
          v-auth="`funds-statistics-histrory`"
          type="primary"
          @click="handleHistory"
          >历史统计数据</el-button
        >
        <el-button
          v-auth="`funds-statistics-export`"
          type="primary"
          @click="handleExport"
          >导出</el-button
        >
      </div> -->
      <el-form
        :inline="true"
        class="demo-form-inline"
        :model="formInline"
        ref="formRef"
        @submit.prevent
      >
        <el-form-item label="单据编号" prop="inputNum">
          <el-input
            v-model.trim="formInline.inputNum"
            clearable
            class="width-custom120"
          ></el-input>
        </el-form-item>

        <el-form-item label="填报时间">
          <el-date-picker
            class="width-custom220"
            v-model="timeValue"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
            @change="handleChangeDate"
          />
        </el-form-item>
        <el-form-item label="状态" prop="approveStatus">
          <el-select
            v-model="formInline.approveStatus"
            clearable
            class="width-custom120"
          >
            <el-option
              v-for="item in approveStatusOptions"
              :key="item.key"
              :value="item.key"
              :label="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="填报类型" prop="inputType">
          <el-select
            v-model="formInline.inputType"
            clearable
            class="width-custom120"
          >
            <el-option
              v-for="item in inputTypeOptions"
              :key="item.key"
              :value="item.key"
              :label="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
      <el-table
        :data="state.tableData"
        border
        style="width: 100%"
        v-loading="loading"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      >
        <template #empty>
          <el-empty :image-size="150" description="暂无数据"></el-empty>
        </template>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="inputNum" label="单据编号"></el-table-column>
        <el-table-column prop="deptName" label="填报单位"></el-table-column>
        <el-table-column
          prop="inputTypeName"
          label="填报类型"
        ></el-table-column>

        <el-table-column
          prop="feeSumAmount"
          label="研发费用合计(万元)"
        ></el-table-column>
        <el-table-column prop="createUserName" label="填报人"></el-table-column>

        <el-table-column prop="createTime" label="填报时间"></el-table-column>
        <el-table-column label="审批状态">
          <template #default="{ row }">
            {{
              APPROVAL_STATUS.find(el => el.dicCode === row.approveStatus)
                .dicValue
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.approveStatus !== '1'"
              type="text"
              @click="handleLook(row, 'look')"
              >查看</el-button
            >
            <el-button v-else type="text" @click="handleLook(row, 'edit')"
              >编辑</el-button
            >

            <!-- <el-button
              v-if="
                row.approveStatus === '2' &&
                row.isHandler === 1 &&
                row.nodeStatusCode != 'end'
              "
              type="text"
              @click="handleLook(row, 'approve')"
              >审批</el-button
            > -->
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除该条记录吗？"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button v-auth="`funds-statistics-del`" type="text"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>

            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定废止该条记录吗？"
              @confirm="handleAbolish(row)"
              v-if="
                info?.userId == row.createUser &&
                row.approveStatus != '1' &&
                row.approveStatus != '3' &&
                row.approveStatus != '9'
              "
            >
              <template #reference>
                <el-button type="text">废止</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-skeleton>
  </div>
  <re-pagination
    :total="total"
    v-show="total > 0"
    v-model:page="formInline.pageNum"
    v-model:limit="formInline.pageSize"
    @pagination="handleSearch"
  />
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { APPROVAL_STATUS } from "../../project-funds/detail/types";
import { getInputFundsList, delInputFunds, getAbolish } from "/@/api/funds";
import NotifMessage from "/@/utils/message/notification";
import { storageLocal } from "/@/utils/storage";

const info = storageLocal.getItem("rdms-info");
const approveStatusOptions = [
  { key: 1, value: "草稿" },
  { key: 2, value: "审批中" },
  { key: 3, value: "已审批" },
  { key: 4, value: "驳回" }
];

const inputTypeOptions = [
  { key: 1, value: "月度经费支出" },
  { key: 2, value: "年度经费预算" }
];

const router = useRouter();

const formRef = ref<HTMLFormElement | null>(null) as any;

let loading = ref<boolean>(false);

let total = ref<number>(0);

let timeValue = ref(null);

let formInline = reactive({
  inputNum: "",
  createUserName: "",
  pageSize: 10,
  pageNum: 1,
  createStartTime: "",
  createEndTime: "",
  approveStatus: "", // 状态 1，2，3，4
  inputType: "" // 状态 1，2
});

let state = reactive({
  tableData: []
});
// 请求列表表格数据
async function getTableData(obj: object = {}) {
  // 真实请求待添加
  loading.value = true;
  try {
    const { code, data } = await getInputFundsList(obj);
    if (code === 200) {
      state.tableData = data.list;
      total.value = data.rows;
    }
  } catch (err) {
    console.log(err);
  } finally {
    loading.value = false;
  }
}

// 清除表单，重置。
const handleReset = () => {
  timeValue.value = null;
  handleChangeDate(null);
  formInline.pageNum = 1;
  formRef.value.resetFields();
};

const handleChangeDate = item => {
  if (item) {
    formInline.createStartTime = item[0];
    formInline.createEndTime = item[1];
  } else {
    formInline.createStartTime = "";
    formInline.createEndTime = "";
  }
};

// 根据条件进行搜索
const handleSearch = (): void => {
  getTableData(formInline);
};

// 删除记录
const handleDelete = async item => {
  try {
    const { code, message } = await delInputFunds({
      inputId: item.id,
      inputType: item.inputType
    });
    if (code === 200) {
      NotifMessage.success(`${message}`);
      getTableData();
    } else {
      NotifMessage.error(`${message}`);
    }
  } catch (err) {
    console.log(err);
  }
};

// 废止记录
const handleAbolish = async item => {
  try {
    const { code, message } = await getAbolish({
      id: item.id
    });
    if (code === 200) {
      NotifMessage.success(`${message}`);
      getTableData();
    } else {
      NotifMessage.error(`${message}`);
    }
  } catch (err) {
    console.log(err);
  }
};

const handleLook = (row, mode): void => {
  switch (row.inputType) {
    case "1":
      router.push({
        path: "/funds/statistics/month",
        query: {
          id: row.id,
          flowId: row.flowId,
          taskId: row.curTaskId,
          instanceId: row.instanceId,
          nodeId: row.nodeStatusCode && row.nodeStatusCode.toLocaleUpperCase(),
          approvalTypeCode: row.approvalTypeCode,
          approvalTypeName: row.approvalTypeName,
          mode: mode,
          name: row.createUserName
        }
      });
      break;
    case "2":
      router.push({
        path: "/funds/statistics/year",
        query: {
          id: row.id,
          flowId: row.flowId,
          taskId: row.curTaskId,
          instanceId: row.instanceId,
          nodeId: row.nodeStatusCode && row.nodeStatusCode.toLocaleUpperCase(),
          approvalTypeCode: row.approvalTypeCode,
          approvalTypeName: row.approvalTypeName,
          mode: mode,
          name: row.createUserName
        }
      });
      break;
  }
};

defineExpose({
  getTableData,
  formInline
});

// 请求数据
getTableData(formInline);
</script>
